﻿using System;
using System.Net;
using System.Net.NetworkInformation;
using Domain.NetworkService.Behaviors.Interfaces;

namespace Domain.NetworkService
{
    public class EchoTestBehavior : INetworkServiceTest
    {
        IPAddress ip;
        int responseTime;
        int size;
        bool dontFragment;
        int ttl;
        public EchoTestBehavior(IPAddress ip,
                                TimeSpan timeout,
                                int size = 32,
                                bool dontFragment = false,
                                int responseTime = 5000,
                                int ttl = 50
                           )
        {
            this.ip = ip;
            this.responseTime = responseTime;
            this.size = size;
            this.dontFragment = dontFragment;
            this.ttl = ttl;
            this.Timeout = timeout;
            this.Description = new EchoDescription()
            {
                networkTestDescription = NetworkTestDescription.ECHO,
                Special = Stub.Absent,
                Timeout = timeout,
                HostNameOrIP = ip.ToString(),
                DontFragment = dontFragment,
                ResponseTime = responseTime,
                Size = size,
                Ttl = ttl
            };
        }

        public NetworkTestResult Start()
        {
            IPAddress ip = this.ip;
            Ping ping = new Ping();
            PingOptions pingOptions = new PingOptions();
            pingOptions.DontFragment = dontFragment;
            pingOptions.Ttl = ttl;
            PingReply pingReply;
            try
            {
                pingReply = ping.Send(ip, responseTime, new byte[size], pingOptions);
            }
            catch
            {
               return new EchoResult()
                {
                    VarDateTime = DateTime.Now,
                    Status = IPStatus.Unknown,
                    Rtt = (long)Rtt.error,
                    IP = this.ip
                };
            }
            if (pingReply.Status == IPStatus.Success)
            {
                return new EchoResult()
                {
                    VarDateTime = DateTime.Now,
                    Status = pingReply.Status,
                    Rtt = pingReply.RoundtripTime,
                    IP = pingReply.Address,
                };
            }
            else
            {
                return new EchoResult()
                {
                    VarDateTime = DateTime.Now,
                    Status = pingReply.Status,
                    Rtt = (long)Rtt.error,
                    IP = this.ip
                };
            }
        }
        public IDescription Description { get; set; }
        public TimeSpan Timeout { get; set; }
    }
}

